package com.spicesoft.clientobjects.samples.form;

import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import com.jgoodies.binding.adapter.BasicComponentFactory;
import com.jgoodies.binding.beans.PropertyAdapter;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import com.spicesoft.clientobjects.BeanEnhancer;

public class AddressPanel extends JPanel {

  private static final long serialVersionUID = 1L;

  private Address address;

  private String title;

  private int rows = 0;

  private CellConstraints cc = new CellConstraints();

  public AddressPanel(Address address, String title) {
    if (address != null) {
      this.address = address;
    } else {
      address = new Address();
      this.address = BeanEnhancer.addPropertyChangeSupport(address);
    }
    this.title = title;

    initUI();
  }

  private void initUI() {
    FormLayout layout = new FormLayout("5dlu, p, 5dlu, p:g, 5dlu",
        "3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu");
    this.setLayout(layout);
    this.setBorder(BorderFactory.createTitledBorder(this.title));

    addTextField(Address.ADDRESS_LINE_1, "Address Line 1");
    addTextField(Address.ADDRESS_LINE_2, "Address Line 2");
    addTextField(Address.CITY, "City");
    addTextField(Address.PROVINCE, "Province");
    addTextField(Address.COUNTRY, "Country");
    addTextField(Address.POSTAL_CODE, "Zip/Postal Code");
  }

  private void addTextField(String fieldName, String labelText) {
    PropertyAdapter adapter = new PropertyAdapter(address, fieldName, true);
    JTextField field = BasicComponentFactory.createTextField(adapter, true);
    rows++;
    this.add(new JLabel(labelText), cc.xy(2, 2 * rows));
    this.add(field, cc.xy(4, 2 * rows));
  }

}
